import React, { PureComponent } from 'react'

import { Map } from 'immutable'

import './select.less'

class Select extends PureComponent {
  static defaultProps = {
    theme: 'night',
    className: '',
    style: {},
    textContainerClassName: '',
    arrowClassName: '',
    dropDownContainerClassName: '',
    dropDownRowClassName: '',
    dataSource: [],
    showKey: '',
    defaultValue: '--',
    value: '',
    renderValue: null,
    renderDropDownRow: null,
    onDataSelected: () => {}
  }

  constructor (props) {
    super(props)
    this.state = {
      value: props.value || props.defaultValue
    }
  }

  static getDerivedStateFromProps (props) {
    if (props.value) {
      return {
        value: props.value
      }
    }
  }

  onRowClick = (data) => () => {
    const { showKey, value, onDataSelected } = this.props
    const v = Map.isMap(data) ? data.get(showKey) : typeof data === 'object' ? data[showKey] : data
    if (!value) {
      this.setState({
        value: v
      })
    }
    onDataSelected(data)
  }

  render () {
    const {
      theme, className, style,
      textContainerClassName, arrowClassName,
      dropDownContainerClassName, dropDownRowClassName,
      dataSource, showKey,
      renderValue, renderDropDownRow
    } = this.props
    const { value } = this.state
    return (
      <div className={`select-${theme} ${className}`} style={style}>
        <div className={`select-text-container ${textContainerClassName}`}>
          <span className="select-text">{(renderValue && renderValue(value)) || value}</span>
          <i className={`select-arrow ${arrowClassName}`}/>
        </div>
        <ul className={`select-drop-down-container ${dropDownContainerClassName}`}>
          {
            dataSource.map((data, index) => {
              return (
                <li
                  key={`key${index}`}
                  className={dropDownRowClassName}
                  onClick={this.onRowClick(data)}>
                  {
                    (renderDropDownRow && renderDropDownRow(data)) ||
                    (Map.isMap(data) ? data.get(showKey) : typeof data === 'object' ? data[showKey] : data)
                  }
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}

export default Select
